<template>
	<view>
		<picker :range="array" range-key="name" mode="multiSelector" @change="bindMultiPickerChange" @columnchange="bindMultiPickerColumnChange" :value="value">
			<slot></slot>
		</picker>
	</view>
</template>

<script>
const $return = require('../../request/api/v1/returnGood.js');

export default {
	data() {
		return {
			array: [],
			value: [0, 0, 0]
		};
	},
	props: {
		defaultIndex: {
			type: Array,
			default: () => []
		}
	},
	mounted: function() {
		this.getRegion();
	},
	/**
	 * 组件的方法列表
	 */
	methods: {
		getRegion() {
			$return.getRegion().then(res => {
				let defaultIndex = this.defaultIndex;
				let province = res;
				let city = [];
				let county = [];
				let value = [0, 0, 0];
				res.forEach((province_item, province_index) => {
					if (province_item.id == defaultIndex[0]) {
						value[0] = province_index;
						city = province_item.child;
						province_item.child.forEach((city_item, city_index) => {
							if (city_item.id == defaultIndex[1]) {
								value[1] = city_index;
								county = city_item.child;
								city_item.child.forEach((county_item, county_index) => {
									if (county_item.id == defaultIndex[2]) {
										value[2] = county_index;
									}
								});
							}
						});
					}
				});
				this.array = [province, city, county];
				this.value = value;
			});
		},

		bindMultiPickerChange(e) {
			let { value } = e.detail;
			let val = [];
			let code = [];
			this.array[0].forEach((province_item, province_index) => {
				if (value[0] == province_index) {
					val[0] = province_item.name;
					code[0] = province_item.id;
					province_item.child.forEach((city_item, city_index) => {
						if (value[1] == city_index) {
							val[1] = city_item.name;
							code[1] = city_item.id;
							city_item.child.forEach((county_item, county_index) => {
								if (value[2] == county_index) {
									val[2] = county_item.name;
									code[2] = county_item.id;
								}
							});
						}
					});
				}
			});
			this.$emit('onChange', {
				detail: {
					value: val,
					code
				}
			});
			this.$emit("change", {
			  data: val,
			});
		},

		bindMultiPickerColumnChange(e) {
			let { column, value } = e.detail;
			let array = this.array;

			switch (column) {
				case 0:
					array[1] = array[0][value].child;
					array[2] = array[1][0].child;
					this.array = array;
					this.value = [value, 0, 0];
					break;

				case 1:
					array[2] = array[1][value].child;
					this.array = array;
					this.value = [this.value[0], value, 0];
					break;

				default:
					break;
			}
		},
	}
};
</script>
<style>
@import './province.css';
</style>
